package com.ray.eye.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ray.base.Constants;
import com.ray.base.adapter.CommonRecyclerAdapter;
import com.ray.base.adapter.MultiTypeSupport;
import com.ray.base.adapter.ViewHolder;
import com.ray.base.base.BaseFragment;
import com.ray.base.bean.video.AllRec;
import com.ray.base.router.RouterActivityPath;
import com.ray.base.router.RouterFragmentPath;
import com.ray.base.utils.StringUtils;
import com.ray.base.utils.TimeUtils;
import com.ray.base.utils.Utils;
import com.ray.eye.R;
import com.ray.eye.databinding.FragmentDailyBinding;
import com.ray.eye.viewmodel.DailyViewModel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 日报
 **/
@Route(path = RouterFragmentPath.Video.PAGER_DAILY)
public class DailyFragment extends BaseFragment<FragmentDailyBinding, DailyViewModel> {

    private List<AllRec.ItemListBeanX> mList = new ArrayList<>();
    private CommonRecyclerAdapter<AllRec.ItemListBeanX> adapter;
    private int num = 0;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_daily;
    }

    @Override
    public void loadData() {
        //获取当前时间
        final Date date = new Date(System.currentTimeMillis());
        //请求数据
        requestDaily(date);
        initAdapter();
        binding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                num -= 2;
                requestDaily(date);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                num = 0;
                requestDaily(date);
            }
        });
    }

    private void requestDaily(Date date) {
        viewModel.getDaily(TimeUtils.date2TimeStamp(date, num, "yyyy-MM-dd HH:mm:ss"), 2).observe(this, new Observer<AllRec>() {
            @Override
            public void onChanged(AllRec allRec) {
                binding.refreshLayout.finishRefresh();
                binding.refreshLayout.finishLoadMore();
                if (allRec != null) {
                    if (num == 0) {
                        mList.clear();
                    }
                    mList.addAll(allRec.getItemList());
                    adapter.notifyDataSetChanged();
                } else {
                    binding.refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
    }


//    日报
//    TextCard   		标题栏(今日社区精选)
//    FollowCard		详细内容

    private void initAdapter() {
        MultiTypeSupport multiTypeSupport = new MultiTypeSupport() {
            @Override
            public int getLayoutId(Object item, int position) {
                //日报里有两种格式类型
//                TextCard   		标题栏(今日社区精选)
//                FollowCard		详细内容
                if (mList.get(position).getData() != null) {
                    switch (mList.get(position).getData().getDataType()) {
                        case Constants.DataType.FollowCard:
                            return R.layout.item_follow_card;
                        case Constants.DataType.TextCard:
                            if (mList.get(position).getData().getType().contains(Constants.DataType.footer)) {
                                return R.layout.item_text_card_with_tagid;
                            } else {
                                return R.layout.item_text_card;
                            }
                        default:
                            return R.layout.item_horizontal_scroll_card;
                    }
                } else {
                    return R.layout.item_horizontal_scroll_card;
                }
            }
        };

        if (adapter == null) {
            adapter = new CommonRecyclerAdapter<AllRec.ItemListBeanX>(getContext(), mList, multiTypeSupport) {
                @Override
                public void convert(ViewHolder holder, final AllRec.ItemListBeanX item, int position) {
                    switch (item.getData().getDataType()) {
                        case Constants.DataType.TextCard:
                            if (item.getData() != null) {
                                holder.setText(R.id.text, item.getData().getText());
                            }
                            break;
                        case Constants.DataType.FollowCard:
                            if (item.getData() != null && item.getData().getContent() != null && item.getData().getContent().getData() != null) {
                                if (item.getData().getContent().getData().getCover() != null) {
                                    //封面图
                                    holder.setImageByGlide(R.id.detail, item.getData().getContent().getData().getCover().getDetail());
                                }
                                if (item.getData().getContent().getData().getAuthor() != null) {
                                    //作者头像
                                    holder.setCircleByGlide(R.id.icon, item.getData().getContent().getData().getAuthor().getIcon());
                                } else if (item.getData().getContent().getData().getOwner() != null) {
                                    //今日社区精选作者头像和作者名字
                                    holder.setCircleByGlide(R.id.icon, item.getData().getContent().getData().getOwner().getAvatar());
                                    holder.setText(R.id.slogan, item.getData().getContent().getData().getOwner().getNickname());
                                }
                                //内容标题
                                if (StringUtils.isEmpty(item.getData().getContent().getData().getTitle())) {
                                    holder.setText(R.id.title, item.getData().getContent().getData().getDescription());
                                } else {
                                    holder.setText(R.id.title, item.getData().getContent().getData().getTitle());
                                }
                                //类型
                                if (!StringUtils.isEmpty(item.getData().getContent().getData().getSlogan())) {
                                    holder.setText(R.id.slogan, item.getData().getContent().getData().getSlogan());
                                } else if (!StringUtils.isEmpty(item.getData().getContent().getData().getCategory())) {
                                    holder.setText(R.id.slogan, item.getData().getContent().getData().getCategory());
                                }
                                //视频时长
                                if (item.getData().getContent().getData().getDuration() != 0) {
                                    holder.setText(R.id.duration, TimeUtils.formatVideoTime((long) item.getData().getContent().getData().getDuration()));
                                    holder.setViewVisibility(R.id.duration, View.VISIBLE);
                                } else {
                                    holder.setViewVisibility(R.id.duration, View.GONE);
                                }
                            }
                            break;
                    }
                    holder.setOnIntemClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (item.getData() != null && item.getData().getContent() != null && item.getData().getContent().getData() != null && !StringUtils.isEmpty(item.getData().getContent().getData().getPlayUrl())) {
                                jumpVideoPlay(item.getData().getContent().getData().getPlayUrl(), item.getData().getContent().getData().getTitle(), item.getData().getContent().getData().getId(), item.getData().getContent().getData().getDescription()
                                ,item.getData().getContent().getData().getDuration(),item.getData().getContent().getData().getCategory(),item.getData().getContent().getData().getCover().getDetail());
                            } else if (item.getData() != null && !StringUtils.isEmpty(item.getData().getActionUrl())) {
                                if (item.getData().getActionUrl().contains("http")) {
                                    String actionUrl = item.getData().getActionUrl();
                                    jump2WebActivity(Utils.decode(actionUrl.substring(actionUrl.indexOf("&url=") + 5)));
                                }
                            }
                        }
                    });
                }
            };
        }
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerView.setAdapter(adapter);
    }

    private void jumpVideoPlay(String url, String title, String id, String desc, long duration, String category, String detail) {
        ARouter.getInstance()
                .build(RouterActivityPath.EyeVideo.PAGER_PLAY)
                .withString("url", url)
                .withString("title", title)
                .withString("id", id)
                .withString("desc", desc)
                .withLong("duration", duration)
                .withString("category", category)
                .withString("detail", detail)
                .navigation();
    }

    private void jump2WebActivity(String url) {
        ARouter.getInstance()
                .build(RouterActivityPath.AdWeb.PAGER_ADDETAIL)
                .withString(Constants.JUMP_KEY_ADURL, url)
                .navigation();
    }
}
